import { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import * as Taro from '@tarojs/taro';
import { THEME_COLORS, TabItem } from '../../constants';
import './index.less';

interface TabBarProps {
  tabs: TabItem[];
  className?: string;
}

const TabBar: React.FC<TabBarProps> = ({ tabs, className = '' }) => {
  const [currentPath, setCurrentPath] = useState('');

  useEffect(() => {
    // 获取当前页面路径
    const pages = Taro.getCurrentPages();
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1];
      setCurrentPath(`/${currentPage.route}`);
    }
  }, []);

  const handleTabClick = (path: string) => {
    // 使用 Taro 导航 API 跳转页面
    if (path === currentPath) {
      // 如果是当前页面，不进行跳转
      return;
    }

    // 判断是否为 tabBar 页面，使用 switchTab
    const isTabBarPage = tabs.some(tab => tab.path === path);

    if (isTabBarPage) {
      Taro.switchTab({
        url: path,
        fail: () => {
          // 如果 switchTab 失败，尝试使用 navigateTo
          Taro.navigateTo({
            url: path,
            fail: () => {
              Taro.showToast({
                title: '页面暂未开发',
                icon: 'none'
              });
            }
          });
        }
      });
    } else {
      Taro.navigateTo({
        url: path,
        fail: () => {
          Taro.showToast({
            title: '页面暂未开发',
            icon: 'none'
          });
        }
      });
    }
  };

  return (
    <View className={`tabbar-container ${className}`}>
      <View className='tabbar-nav'>
        {tabs.map((tab) => {
          const isActive = currentPath === tab.path;
          return (
            <View
              key={tab.id}
              className={`tabbar-item ${isActive ? 'tabbar-item-active' : ''}`}
              onClick={() => handleTabClick(tab.path)}
              style={{
                color: isActive ? THEME_COLORS.primary : THEME_COLORS.secondary
              }}
            >
              <Text className='tabbar-icon'>
                {tab.icon}
              </Text>
              <Text className='tabbar-label'>{tab.label}</Text>
            </View>
          );
        })}
      </View>
    </View>
  );
};

export default TabBar;
